#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>

int main(int argc,char *argv[]){

    char c;
    int i = 0;
    int fd;  

    const char *filename = "abc.txt";
    FILE *fp = fopen(filename,"r+");
    fd = fileno(fp); 

    if(fp == NULL){
        printf("Error: Could not open file %s\n",filename);
        exit(1);
    }
    printf("打开文件后，文件的位置是： %ld \n",ftell(fp));

    while((c = fgetc(fp))!= EOF){
        if(c == '\n') c='-';
        printf("%d:%c; ",i,c);
        i++;
    }
    printf("\n当文件移到最后时，偏移是：%ld",ftell(fp));
    int offset = 23;
    fseek(fp,offset,SEEK_SET);
    printf("\n 调用fseek()后的位置是%ld ",ftell(fp));
    c = fgetc(fp);
    printf("\n%d 这个位置的字符是: %c",offset,c);
    printf("\n");
    c = fgetc(fp);
    printf("\n%d 这个位置的字符是: %c",offset+1,c);
    printf("\n");
    // fwrite("hello",1,5,fp);
    fflush(fp);
    fseek(fp,0,SEEK_SET);
    printf("写入文字后，重新输出文件内容：\n");
    while((c = fgetc(fp)) != EOF){
        printf("%c",c);
    }

    int filesize = fseek(fp,0,SEEK_END);
    printf("\n文件大小是：%d\n",ftell(fp));

    struct stat st;
    fstat(fd,&st);
    printf("文件大小是：%ld\n",st.st_size);

    fclose(fp);
    return 0;
}